package com.easylive.admin.interceptor;

import com.easylive.entity.component.RedisComponent;
import com.easylive.entity.constants.Constants;
import com.easylive.entity.enums.ResponseCodeEnum;
import com.easylive.entity.vo.ResponseVO;
import com.easylive.exception.BusinessException;
import com.easylive.utils.JsonUtil;
import com.easylive.utils.StringTools;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @Author: yudaxian
 * @Description: admin拦截器
 * @DateTime: 2024/11/3 14:57
 **/
@Component
public class AppInterceptor implements HandlerInterceptor {

    @Resource
    private RedisComponent redisComponent;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (ObjectUtils.isEmpty(handler)) {
            return false;
        }
        String adminToken = getAdminToken(request);
        if (StringTools.isEmpty(adminToken)) {
            setResponse(response, ResponseCodeEnum.CODE_901);
            return false;
        }
        String adminAccountByToken = redisComponent.getAdminAccountByToken(adminToken);
        if (StringTools.isEmpty(adminAccountByToken)) {
            setResponse(response, ResponseCodeEnum.CODE_901);
            return false;
        }
        if (handler instanceof HandlerMethod) {
            return true;
        } else {
//            setResponse(response, ResponseCodeEnum.CODE_404);
            throw new BusinessException("404 Not Found");
//            return false;
        }
    }

    private String getAdminToken(HttpServletRequest request) {
        String headerToken = request.getHeader(Constants.COOKIE_TOKEN_ADMIN);
        if (!StringTools.isEmpty(headerToken)) {
            return headerToken;
        }
        Cookie[] cookies = request.getCookies();
        if (ObjectUtils.isEmpty(cookies)) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (Objects.equals(cookie.getName(), Constants.COOKIE_TOKEN_ADMIN)) {
                return cookie.getValue();
            }
        }
        return null;
    }

    private void setResponse(HttpServletResponse response, ResponseCodeEnum responseCodeEnum) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        ResponseVO ajaxResponse = new ResponseVO();
        ajaxResponse.setCode(responseCodeEnum.getCode());
        ajaxResponse.setInfo(responseCodeEnum.getMsg());
        ajaxResponse.setStatus("error");
        response.getWriter().write(JsonUtil.convertObjToStr(ajaxResponse));
        response.getWriter().flush();
    }
}
